/*
 * @Author: 黄达全
 * @Date: 2024-08-20 11:26:10
 * @LastEditTime: 2024-08-20 16:35:17
 */

export default class WebSocketClient {

    private ws: WebSocket | null = null;
    private messageCallback: ((data: any) => void) | null = null;
    private openCallback: (() => void) | null = null;
    constructor(private url: string) {
        this.url = url;
        this.connect()
    }

    private connect(): void {
        if (this.ws) {
            console.warn("WebSocket已经连接");
            return
        }
        this.ws = new WebSocket(this.url);

        this.ws.onopen = () => {
            console.log("WebSocket is open now.");
            if (this.openCallback) {
                this.openCallback();
            }
        };

        this.ws.onmessage = (event: MessageEvent) => {
            if (this.messageCallback) {
                this.messageCallback(event.data);
            }
        };

        this.ws.onerror = (error: Event) => {
            console.log("WebSocket error: ", error);
        };

        this.ws.onclose = () => {
            console.log("WebSocket is closed now.");
            this.ws = null; // Clean up the WebSocket instance
        };
    }

    public sendMessage(message: string): void {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(message);
        } else {
            console.error("WebSocket未连接");
        }
    }

    public onMessage(callback: (data: any) => void): void {
        this.messageCallback = callback;
    }
    public onOpen(callback: () => void): void {
        this.openCallback = callback;
    }
}